package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.common.util.ReflectionUtils;
import com.settlement.system.mapper.TbOrderMapper;
import com.settlement.system.model.entity.SysPlatform;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.entity.TbOrder;
import com.settlement.system.model.query.TbOrderPageQuery;
import com.settlement.system.model.vo.TbOrderImportVo;
import com.settlement.system.service.TbOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 淘宝订单表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-05
 */
@Service
@RequiredArgsConstructor
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements TbOrderService {

    @Override
    public Page<TbOrder> getTbOrderPage(TbOrderPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        String tableName = "tb_order_%s".formatted(queryParams.getBillMonth());
        queryParams.setTableName(tableName);
        if (!StringUtils.hasText(this.baseMapper.existTable(tableName))) {
            return new Page<>(pageNum, pageSize);
        }
        // 查询数据
        Page<TbOrder> page = new Page<>(pageNum, pageSize);
        Page<TbOrder> orderPage = this.baseMapper.getPage(page, queryParams);
        return orderPage;
    }


    @Override
    public void addImportData(List<TbOrderImportVo> vos, SysStore sysStore, SysPlatform sysPlatform, Map<String, String> linkNoMap) {
        List<String> billMonthList = new ArrayList<>();
        for (TbOrderImportVo vo : vos) {
            if (vo.getOrderCreateTime() != null) {
                String billMonth = DateUtils.formatDate(vo.getOrderCreateTime());
                if (!billMonthList.contains(billMonth)) {
                    billMonthList.add(billMonth);
                }
            }
        }
        List<String> orderNos = vos.stream().map(TbOrderImportVo::getOrderNo).filter(StringUtils::hasText).toList();
        // 所有存在的记录
        List<TbOrder> list = new ArrayList<>();
        for (String billMonth : billMonthList) {
            TbOrderPageQuery pageQuery = new TbOrderPageQuery();
            pageQuery.setOrderNos(orderNos);
            pageQuery.setTableName("tb_order_%s".formatted(billMonth));
            // 根据账单日期查询对应表的核销数据
            List<TbOrder> dyOrderList = this.baseMapper.getList(pageQuery);
            if (dyOrderList != null && dyOrderList.size() > 0) {
                list.addAll(dyOrderList);
            }
        }
        // 需要新建的列表
        List<TbOrderImportVo> createVos = new ArrayList<>();
        // 需要更新的列表
        List<TbOrderImportVo> updateVos = new ArrayList<>();
        for (TbOrderImportVo vo : vos) {
            Map<String, String> fieldAnnotation = ReflectionUtils.getFieldAnnotation(vo);
            fieldAnnotation.forEach((key, value) -> {
                try {
                    Field declaredField = vo.getClass().getDeclaredField(key);
                    declaredField.setAccessible(true);
                    if (StringUtils.hasText(value) && (value.equals("null") || value.equals("'null"))) {
                        declaredField.set(vo, null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            TbOrder record = list.stream().filter(tbOrder -> tbOrder.getOrderNo().equals(vo.getOrderNo())).findFirst().orElse(null);
            if (record == null) {
                // 加入到新建列表
                createVos.add(vo);
            } else {
                // 加入到更新列表
                updateVos.add(vo);
            }
        }
        List<String> columnList = TbOrder.getDateColumn();
        columnList.add("id");
        columnList.add("storeId");
        for (TbOrderImportVo updateVo : updateVos) {
            // 更新操作
            list.stream().filter(tbOrder -> tbOrder.getOrderNo().equals(updateVo.getOrderNo())).findFirst().ifPresent(tbOrder -> {
                BeanUtil.copyProperties(updateVo, tbOrder, columnList.toArray(new String[0]));
                tbOrder.setOrderCreateTime(updateVo.getOrderCreateTime());
                tbOrder.setOrderPayTime(DateUtils.convert(updateVo.getOrderPayTime()));
                tbOrder.setReceiveTime(DateUtils.convert(updateVo.getReceiveTime()));
                tbOrder.setExperienceEndTime(DateUtils.convert(updateVo.getExperienceEndTime()));
                tbOrder.setDeliveryTime(DateUtils.convert(updateVo.getDeliveryTime()));
                tbOrder.setTableName("tb_order_%s".formatted(DateUtils.formatDate(tbOrder.getOrderCreateTime())));
                this.baseMapper.update(tbOrder);
            });
        }
        for (TbOrderImportVo vo : createVos) {
            TbOrder tbOrder = new TbOrder();
            BeanUtil.copyProperties(vo, tbOrder, columnList.toArray(new String[0]));
            tbOrder.setOrderCreateTime(vo.getOrderCreateTime());
            tbOrder.setOrderPayTime(DateUtils.convert(vo.getOrderPayTime()));
            tbOrder.setReceiveTime(DateUtils.convert(vo.getReceiveTime()));
            tbOrder.setExperienceEndTime(DateUtils.convert(vo.getExperienceEndTime()));
            tbOrder.setDeliveryTime(DateUtils.convert(vo.getDeliveryTime()));
            tbOrder.setTableName("tb_order_%s".formatted(DateUtils.formatDate(tbOrder.getOrderCreateTime())));
            tbOrder.setPlatform(sysPlatform.getPlatformKey());
            tbOrder.setStoreId(sysStore.getId());
            tbOrder.setStoreName(sysStore.getCommercePlatformStoreName());
            tbOrder.setAuditNo(linkNoMap.get(tbOrder.getOrderNo()));
            tbOrder.setBillMonth(linkNoMap.get(tbOrder.getOrderNo() + "账单月份"));
            // 判断历史表是否存在，不存在则新增
            if (!StringUtils.hasText(this.baseMapper.existTable(tbOrder.getTableName()))) {
                this.createTable(tbOrder.getTableName());
            }
            this.baseMapper.insertData(tbOrder);
        }
    }

    @Override
    public boolean createTable(String tableName) {
        return this.getBaseMapper().createTable(tableName) > 0;
    }

    @Override
    public List<TbOrder> getList(TbOrderPageQuery queryParams) {
        return this.baseMapper.getList(queryParams);
    }
}
